﻿using System;
using System.Linq;
using System.ServiceModel.DomainServices.Client;
using System.Windows.Controls;
using System.Windows.Printing;
using MedLink2011.Core;
using MedLink2011.Views.Patients.ChildWindows;
using MedLink2011.Views.Patients.Reports;
using MedLink2011.Web.Models;
using MedLink2011.Web.Services;
using System.Collections.ObjectModel;
using System.Windows;
using Telerik.Windows.Controls.GridView;
using RelayCommand = MedLink2011.Core.RelayCommand;
using System.Windows.Browser;
using MedLink2011.Controls;

namespace MedLink2011.Views.Patients.ViewModels
{
    public class PediatricPSCViewModel : PerformAsyncQueryBase // the AsyncQuery one inherits from ViewModel Base
    {
        public static MedLink2011Context _pediatricPSCDomainContext;
        private ObservableCollection<PediatricPSC> _pediatricPSC;
        private MedLink2011Context _context;
        private EntityQuery<MedLink2011.Web.Models.Patient> _patientQuery;
        private EntityQuery<MedLink2011.Web.Models.Doctor> _doctorQuery;
        //
       public PediatricPSCViewModel()
        {
            if (!IsDesignTime)
            {
                _pediatricPSCDomainContext = new MedLink2011Context();
                IsBusy = true;
                WireCommands();
                LoadPediatricPSCAsync();
                LoadComboBoxData();
            }
        }
        
        #region "Load Current PediatricPSC"
        readonly int loadedPatient_Id = MedLink2011.Views.Patients.ViewModels.PatientViewModel.DashLoad_PK;
        //readonly int loadedPatient_Id = 1;
        private void LoadPediatricPSCAsync()
         {
           if (!_pediatricPSCDomainContext.IsSubmitting)
            {
                if (loadedPatient_Id > 0)
                {
                    PerformAsyncQuery<PediatricPSC>(_pediatricPSCDomainContext, _pediatricPSCDomainContext.GetPediatricPsCsForPatientsQuery(loadedPatient_Id), PediatricPSCLoadedComplete);
                }
                else
                {
                    PerformAsyncQuery<PediatricPSC>(_pediatricPSCDomainContext, _pediatricPSCDomainContext.GetPediatricPsCsQuery(), PediatricPSCLoadedComplete); 
                }
            }
        }

        private EntitySet<PediatricPSC> _pediatricPSCCollection;
        public EntitySet<PediatricPSC> PediatricPSCCollection
        {
            get { return _pediatricPSCCollection; }
            set
            {
                _pediatricPSCCollection = value;
                RaisePropertyChanged("PediatricPSCCollection");
            }
        }

        private PediatricPSC _currentPediatricPSC;
        public PediatricPSC CurrentPediatricPSC
        {
            get { return _currentPediatricPSC; }
            set
            {
                _currentPediatricPSC = value;
                RaisePropertyChanged("CurrentPediatricPSC");
            }
        }

        #endregion "Load Current PediatricPSC"

        #region Commands

        private void EnableCommands()
        {
            AddNewPediatricPSCCommand.IsEnabled = true;
            SavePediatricPSCCommand.IsEnabled = true;
            DeletePediatricPSCCommand.IsEnabled = true;
            PrintPediatricPSCCommand.IsEnabled = true;
            SearchPediatricPSCCommand.IsEnabled = true;
            SelectionChangedCommand.IsEnabled = true;
            RowLoadedCommand.IsEnabled = true;
            ShowChartDashboardCommand.IsEnabled = true;
           }

        private void WireCommands()
        {
            AddNewPediatricPSCCommand = new RelayCommand(AddPediatricPSC);
            SavePediatricPSCCommand = new RelayCommand(SavePediatricPSC);
            DeletePediatricPSCCommand = new RelayCommand(DeletePediatricPSC);
            PrintPediatricPSCCommand = new RelayCommand(PrintPediatricPSC);
            ShowChartDashboardCommand = new RelayCommand<object>(ShowChartDashboard);
            SearchPediatricPSCCommand = new RelayCommand<string>(SearchInPediatricPSC);
            SelectionChangedCommand = new RelayCommand<Telerik.Windows.Controls.SelectionChangeEventArgs>(e =>
            {
                var element = e.OriginalSource as UIElement;
                var element2 = e.OriginalSource as Telerik.Windows.Controls.DataControl;

                if ((element2 != null) && (!_toDelete))
                {
                    var _theItem = element2.SelectedItem;
                    CurrentPediatricPSC = (PediatricPSC) _theItem;
            SelectedPatient =
                PatientCollection.Where(c => c.Patient_Id == CurrentPediatricPSC.Patient_Id).SingleOrDefault();
            SelectedDoctor =
                DoctorCollection.Where(c => c.Doctor_Id == CurrentPediatricPSC.Doctor_Id).SingleOrDefault();
              }
            });
            
            RowLoadedCommand = new RelayCommand<Telerik.Windows.Controls.GridView.RowLoadedEventArgs>( e =>
                {
                    if (e.Row is GridViewRow && !(e.Row is GridViewNewRow))
                    {
                        MedLink2011.Web.Models.PediatricPSC model = e.DataElement as MedLink2011.Web.Models.PediatricPSC;
                        var grid = new Grid();
                        var tb = new TextBlock
                               {
                               Text = string.Format(
			"Evaluation Date : {0} \r\n"+
			"Psc Score : {1} \r\n"+
			"Complains Of Aches And Pains Spends More Time Alone : {2} \r\n"+
			"Tires Easily Has Little Energy : {3} \r\n"+
			"Fidgety _unable To Sit Still : {4} \r\n"+
			"Has Trouble With Teacher : {5} \r\n"+
			"Less Interested In School : {6} \r\n"+
			"Acts As If Driven By A Motor : {7} \r\n"+
			"Daydreams Too Much : {8} \r\n"+
			"Distracted Easily : {9} \r\n"+
			"Is Afraid Of New Situations : {10} \r\n"+
			"Feels Sad Unhappy : {11} \r\n"+
			"Is Irritable Angry : {12} \r\n"+
			"Feels Hopeless : {13} \r\n"+
			"Has Trouble Concentrating : {14} \r\n"+
			"Less Interested In Friends : {15} \r\n"+
			"Fights With Other Children : {16} \r\n"+
			"Absent From School : {17} \r\n"+
			"School Grades Dropping : {18} \r\n"+
			"Is Down On Him Or Herself : {19} \r\n",

			model.Evaluation_Date_,
			model.PSC_Score,
			model.Complains_of_aches_and_painsSpends_more_time_alone,
			model.Tires_easily__has_little_energy,
			model.Fidgety__unable_to_sit_still,
			model.Has_trouble_with_teacher,
			model.Less_interested_in_school,
			model.Acts_as_if_driven_by_a_motor,
			model.Daydreams_too_much,
			model.Distracted_easily,
			model.Is_afraid_of_new_situations,
			model.Feels_sad__unhappy,
			model.Is_irritable__angry,
			model.Feels_hopeless,
			model.Has_trouble_concentrating,
			model.Less_interested_in_friends,
			model.Fights_with_other_children,
			model.Absent_from_school,
			model.School_grades_dropping,
			model.Is_down_on_him_or_herself
                     ),
                            Margin = new Thickness(3, 3, 3, 3),
                            Opacity = 0.8,
                            MaxWidth = 250,
                            FontSize = 10,
                            TextWrapping = TextWrapping.NoWrap
                                     };
                        grid.Children.Add(tb);
                        ToolTipService.SetToolTip(e.Row, grid);
                    }
                });
                
           }

        public RelayCommand<Telerik.Windows.Controls.GridView.RowLoadedEventArgs> RowLoadedCommand
        {
            get;
            private set;
        }

        public RelayCommand<Telerik.Windows.Controls.SelectionChangeEventArgs> SelectionChangedCommand
        {
            get;
            private set;
        }

        public RelayCommand AddNewPediatricPSCCommand
        {
            get;
            private set;
        }
        public RelayCommand SavePediatricPSCCommand
        {
            get;
            private set;
        }
        public RelayCommand DeletePediatricPSCCommand
        {
            get;
            private set;
        }
        public RelayCommand PrintPediatricPSCCommand
        {
            get;
            private set;
        }

        public RelayCommand<object> ShowChartDashboardCommand
        {
            get;
            private set;
        }

        public RelayCommand<string>  SearchPediatricPSCCommand
        {
            get;
            private set;
        }

        #endregion Commands
        
        private void SearchInPediatricPSC( string searchText)
        {
            MessageBox.Show(searchText);
        }
        
        public void SavePediatricPSC()
        {
            CurrentPediatricPSC.Patient_Id = SelectedPatient.Patient_Id;
            CurrentPediatricPSC.Doctor_Id = SelectedDoctor.Doctor_Id;
            CurrentPediatricPSC.write_date = CurrentTime;
            CurrentPediatricPSC.write_uid = CurrentUser;
            _pediatricPSCDomainContext.SubmitChanges(p =>
            {
                if (p.HasError)
                {
                    p.MarkErrorAsHandled();
                    ErrorWindow.CreateNew(p.Error);
                }
                else
                {
                    MessageBox.Show("PediatricPSC se ha actualizado");
                    RaisePropertyChanged("PediatricPSCCollection");
                    RaisePropertyChanged("CurrentPediatricPSC");
                }
            }, null);
        }
        #region "Add New"
        //http://forums.silverlight.net/forums/p/193377/449256.aspx
        private void AddPediatricPSC()
        {

            MedLink2011.Web.Models.PediatricPSC pediatricPSC = new MedLink2011.Web.Models.PediatricPSC();
            PediatricPSCsAddCW addNewWindow = new PediatricPSCsAddCW();
            addNewWindow.DataContext = pediatricPSC;
            addNewWindow.Closed += (s, ee) =>
            {
                if (addNewWindow.DialogResult == true)
                {
                    pediatricPSC.create_date = CurrentTime;
                    pediatricPSC.write_date = CurrentTime;
                    pediatricPSC.create_uid = CurrentUser;
                    pediatricPSC.write_uid = CurrentUser;
                    
                    _pediatricPSCDomainContext.PediatricPSCs.Add(pediatricPSC);
                    _pediatricPSCDomainContext.SubmitChanges(p =>
                    {
                        if (p.HasError)
                        {
                            p.MarkErrorAsHandled();
                            ErrorWindow.CreateNew(p.Error);
                        }
                        else
                        {
                            MessageBox.Show("New PediatricPSC has been added");
                        }
                    }, null);
                }
            };
            addNewWindow.Show();
            addNewWindow.Closed += FrmClosedAdd;
        }


        void FrmClosedAdd(object sender, EventArgs e)
        {
            LoadPediatricPSCAsync();
        }
        #endregion "Add New"


        private static int _dashload_PK;
        public static int DashLoad_PK
        {
            get { return _dashload_PK; }
            set { _dashload_PK = value ; }
        }


        private void ShowChartDashboard(object selectedItem)
        {
            //
            string a = selectedItem.ToString();
            int i = a.IndexOf(":") + 1;
            a = a.Substring(i);
            int dashLoadPk;
            int.TryParse(a, out dashLoadPk);
            DashLoad_PK = dashLoadPk;
            Uri target = new Uri("/Patients/Pages/PatientsTitlePage?PediatricPSC_id=" + DashLoad_PK, UriKind.Relative);

   
            var _theItem = selectedItem;
            CurrentPediatricPSC = (PediatricPSC)_theItem;
            //NavigationService.Navigate(target);
            //var service = ((Page)((App)Application.Current).RootVisual).NavigationService;
            //if (service != null) service.Navigate(target);
        }



        private static int _current_Patient_id;
        public static int Current_Patient_id
        {
            get { return _current_Patient_id; }
            set { _current_Patient_id = value ; }
        }
        
        private bool _isBusy;
        public bool IsBusy
        {
            get { return _isBusy; }
            set
            {
                _isBusy = value;
                RaisePropertyChanged("IsBusy");
            }
        }
        public string CurrentTime
        {
            get
            {
                DateTime time = DateTime.Now;   
                const string format = "MMM ddd d HH:mm yyyy";  
                return (time.ToString(format));
            }
        }

        public string CurrentUser
        {
            get { return WebContext.Current.User.ToString() ; }
        }


        #region "LoadComboBoxData"

            
        public EntitySet<Patient> PatientCollection { get; set; }
        private Patient _selectedPatient;
        public  Patient SelectedPatient
        {
            get { return _selectedPatient; }
            set
            {
                _selectedPatient = value;
                RaisePropertyChanged("SelectedPatient");
            }
        }
            
        public EntitySet<Doctor> DoctorCollection { get; set; }
        private Doctor _selectedDoctor;
        public  Doctor SelectedDoctor
        {
            get { return _selectedDoctor; }
            set
            {
                _selectedDoctor = value;
                RaisePropertyChanged("SelectedDoctor");
            }
        }
        private long dtStart = 0;
        private long dtEnd = 0;
        void LoadComboBoxData()
        {
            dtStart = System.DateTime.Now.Ticks;
            
            //Patient_IdComboBox
            _context = new MedLink2011Context();
            _patientQuery = _context.GetPatientsQuery();
            _patientQuery = _patientQuery.OrderBy(e => e.Patient_Id);
            PerformAsyncQuery<Patient>(_context, _patientQuery, Patient_IdComboBoxLoaded);
            PatientCollection = _context.Patients;
            
            //Doctor_IdComboBox
            _context = new MedLink2011Context();
            _doctorQuery = _context.GetDoctorsQuery();
            _doctorQuery = _doctorQuery.OrderBy(e => e.Doctor_Id);
            PerformAsyncQuery<Doctor>(_context, _doctorQuery, Doctor_IdComboBoxLoaded);
            DoctorCollection = _context.Doctors;
        }
        
        private void Patient_IdComboBoxLoaded(object sender, MedLink2011.Core.EntityResultsArgs<Patient> e)
        {
            if (!e.HasError)
            {
                SelectedPatient =
                    PatientCollection.Where(c => c.Patient_Id == CurrentPediatricPSC.Patient_Id).SingleOrDefault();
            }
        }
        private void Doctor_IdComboBoxLoaded(object sender, MedLink2011.Core.EntityResultsArgs<Doctor> e)
        {
            if (!e.HasError)
            {
                SelectedDoctor =
                    DoctorCollection.Where(c => c.Doctor_Id == CurrentPediatricPSC.Doctor_Id).SingleOrDefault();
            }
        }


        private void PediatricPSCLoadedComplete(object sender, MedLink2011.Core.EntityResultsArgs<PediatricPSC> e)
        {
            IsBusy = false;
            if (!e.HasError)
            {
                PediatricPSCCollection = _pediatricPSCDomainContext.PediatricPSCs;
                CurrentPediatricPSC = PediatricPSCCollection.FirstOrDefault();
                EnableCommands();
            SelectedPatient = PatientCollection.Where(c => c.Patient_Id == CurrentPediatricPSC.Patient_Id).SingleOrDefault();
            SelectedDoctor = DoctorCollection.Where(c => c.Doctor_Id == CurrentPediatricPSC.Doctor_Id).SingleOrDefault();

            }
            else
            {
                // notify user if there is any error
                //AppMessages.RaiseErrorMessage.Send(e.Error);
            }
        }

        private void AddNewForm_Closed(object sender, MedLink2011.Core.EntityResultsArgs<PediatricPSC> e)
        {
            if (!e.HasError)
            {
                
            }
        }


        #endregion "LoadComboBoxData"

        #region "Delete"

        private bool _toDelete=false;

        private void DeletePediatricPSC()
        {
            _toDelete = true;
            var pediatricPSCToDelete = CurrentPediatricPSC;
           if (pediatricPSCToDelete != null)
                    {
                     var result = MessageBox.Show("Are you sure you wish to delete the Current PediatricPSC?", "Confirm Delete", MessageBoxButton.OKCancel);
                      if (result.Equals(MessageBoxResult.OK))
                        {
            _pediatricPSCDomainContext.PediatricPSCs.Remove(pediatricPSCToDelete);
            _pediatricPSCDomainContext.SubmitChanges(o =>
            {
                if (o.HasError)
                {
                    MessageBox.Show("Esta pediatricPSC no se puede eliminar ya que existen datos que dependen de esta PediatricPSC.....", "Cancelado", MessageBoxButton.OKCancel);
                    o.MarkErrorAsHandled();
                    _pediatricPSCDomainContext.RejectChanges();
                }
                else
                {
                    MessageBox.Show("el registro de  pediatricPSC ha sido eliminado exitosamente ... ");
                    //LoadPediatricPSCAsync();
                    RaisePropertyChanged("PediatricPSCCollection");
                    CurrentPediatricPSC = PediatricPSCCollection.FirstOrDefault();
                }
            }, null);
            }
       }
            _toDelete = false;
        }
        #endregion "Delete"
        
        #region "Print"
        
        private void PrintPediatricPSC()
        {
            if (CurrentPediatricPSC != null)
            {
                PrintDocument document = new PrintDocument();
                document.PrintPage += new System.EventHandler<PrintPageEventArgs>(document_PrintPage); // fires when every single page is going to print 
                document.EndPrint += new System.EventHandler<EndPrintEventArgs>(document_EndPrint); // when printing is completed
                string PrintQueue = "PediatricPSCs_" + CurrentPediatricPSC.ToString(); // to show in the print queue
                document.Print(PrintQueue); //fires when printing has begun
            }
        }
        
        static void document_EndPrint(object sender, EndPrintEventArgs e)
        {
            if (e.Error != null)
            {
                ErrorWindow error = new ErrorWindow(e.Error.Message, e.Error.StackTrace);
            }
            else
                MessageBox.Show("Print Complete");
        }
        
        void document_PrintPage(object sender, PrintPageEventArgs e)
        {
            PrintDocument document = sender as PrintDocument;
            MedLink2011.Web.Models.PediatricPSC appt = CurrentPediatricPSC as MedLink2011.Web.Models.PediatricPSC;
            if (appt != null)
            {
                //e.HasMorePages = appt.ChildEntity != null && document.PrintedPageCount < appt.ChildEntity.Count;
                //if (document.PrintedPageCount > 0)
                //{
                // e.PageVisual = new ChildEntityFReport() { DataDomainContext = appt.ChildEntity.ElementAt(document.PrintedPageCount - 1) };
                //}
                //else
                e.PageVisual = new PediatricPSCsFReport() { DataContext = appt };
            }
        }
       
        #endregion "Print"

    }


}

